<template>
  <view class="container">
    <!-- Result Header -->
    <view :class="resultClass" class="result-header">
      <view class="result-icon">
        <uni-icons :type="resultIcon" color="#ffffff" size="60"></uni-icons>
      </view>
      <view class="result-title">{{ resultTitle }}</view>
      <view class="result-score">{{ scoreResult.score }}分</view>
    </view>

    <!-- Score Details -->
    <view v-if="scoreResult" class="score-details">
      <view class="detail-item">
        <view class="detail-label">正确数量</view>
        <view class="detail-value">{{ scoreResult.correctCount }}/{{ scoreResult.totalQuestions }}</view>
      </view>
      <view class="detail-item">
        <view class="detail-label">正确率</view>
        <view class="detail-value">{{ scoreResult.accuracy }}%</view>
      </view>
      <view class="detail-item">
        <view class="detail-label">练习时间</view>
        <view class="detail-value">{{ formatTime(practiceTime) }}</view>
      </view>
    </view>

    <!-- Answer Review -->
    <view class="answer-review">
      <view class="review-title">答题详情</view>
      <view class="answer-list">
        <view
            v-for="(pair, index) in reviewData"
            :key="index"
            :class="{ 'correct': pair.isCorrect, 'wrong': !pair.isCorrect }"
            class="answer-item"
        >
          <view class="answer-content">
            <view class="fraction">{{ pair.fractionDisplay }}</view>
            <view class="connection-line">
              <uni-icons
                  :color="pair.isCorrect ? '#28a745' : '#dc3545'"
                  :type="pair.isCorrect ? 'checkmarkempty' : 'closeempty'"
                  size="16"
              ></uni-icons>
            </view>
            <view class="decimal">{{ pair.decimalDisplay }}</view>
          </view>
          <view v-if="!pair.isCorrect" class="correct-answer">
            <text>正确答案：{{ pair.correctDecimalDisplay }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- Action Buttons -->
    <view class="actions">
      <button class="action-btn secondary-btn" @tap="tryAgain">
        <uni-icons color="#007AFF" size="20" type="refresh"></uni-icons>
        <text>再次练习</text>
      </button>
      <button class="action-btn primary-btn" @tap="backToHome">
        <uni-icons color="#ffffff" size="20" type="home"></uni-icons>
        <text>返回首页</text>
      </button>
    </view>
  </view>
</template>

<script>
import ScoreCalculator from '@/utils/score-calculator.js';
import CommonUtils from '@/utils/common.js';
import Storage from '@/utils/storage.js';

export default {
  data() {
    return {
      questionData: null,
      userAnswers: [],
      scoreResult: null,
      practiceTime: 0,
      reviewData: []
    }
  },
  computed: {
    resultClass() {
      if (!this.scoreResult) return 'result-normal';
      if (this.scoreResult.isPerfect) return 'result-perfect';
      if (this.scoreResult.accuracy >= 80) return 'result-good';
      if (this.scoreResult.accuracy >= 60) return 'result-normal';
      return 'result-poor';
    },

    resultIcon() {
      if (!this.scoreResult) return 'info';
      if (this.scoreResult.isPerfect) return 'star';
      if (this.scoreResult.accuracy >= 80) return 'checkmarkempty';
      if (this.scoreResult.accuracy >= 60) return 'info';
      return 'closeempty';
    },

    resultTitle() {
      if (!this.scoreResult) return '练习完成';
      if (this.scoreResult.isPerfect) return '完美答题！';
      if (this.scoreResult.accuracy >= 80) return '表现优秀！';
      if (this.scoreResult.accuracy >= 60) return '继续努力！';
      return '需要加强练习';
    }
  },
  onLoad() {
    this.loadResultData();
  },
  methods: {
    // 加载结果数据
    loadResultData() {
      const maxWaitTime = 3000; // 最长等待时间3秒
      const checkInterval = 100; // 每100ms检查一次
      let elapsedTime = 0;

      const checkData = () => {
        const app = getApp();
        const resultData = app.globalData.speedJudgeResult;

        if (resultData) {
          // 找到数据，处理数据
          this.questionData = resultData.questionData;
          this.userAnswers = resultData.userAnswers;
          this.practiceTime = (resultData.endTime - resultData.startTime) / 1000;

          this.calculateScore();
          this.generateReviewData();
          this.saveRecord();

          // 清除全局数据
          app.globalData.speedJudgeResult = null;
          return;
        }

        elapsedTime += checkInterval;

        if (elapsedTime < maxWaitTime) {
          // 继续等待
          setTimeout(checkData, checkInterval);
        } else {
          // 超时，显示错误
          uni.showModal({
            title: '提示',
            content: '未找到练习数据',
            showCancel: false,
            success: () => {
              this.backToHome();
            }
          });
        }
      };

      checkData();
    },

    // 计算分数
    calculateScore() {
      this.scoreResult = ScoreCalculator.calculateSpeedJudgeScore(
          this.questionData.correctPairs,
          this.userAnswers
      );
    },

    // 生成复习数据
    generateReviewData() {
      this.reviewData = this.questionData.fractions.map(fraction => {
        const userAnswer = this.userAnswers.find(answer =>
            answer.fractionId === fraction.id
        );

        const correctPair = this.questionData.correctPairs.find(pair =>
            pair.fractionId === fraction.id
        );

        const correctDecimal = this.questionData.decimals.find(decimal =>
            decimal.id === correctPair.decimalId
        );

        const userDecimal = userAnswer ?
            this.questionData.decimals.find(decimal => decimal.id === userAnswer.decimalId) :
            null;

        return {
          fractionDisplay: fraction.display,
          decimalDisplay: userDecimal ? userDecimal.display : '未连线',
          correctDecimalDisplay: correctDecimal.display,
          isCorrect: userAnswer && userAnswer.decimalId === correctPair.decimalId
        };
      });
    },

    // 保存记录
    saveRecord() {
      const record = {
        type: 'speed-judge',
        questionCount: this.questionData.fractions.length,
        correctCount: this.scoreResult.correctCount,
        accuracy: this.scoreResult.accuracy,
        score: this.scoreResult.score,
        practiceTime: this.practiceTime,
        isPerfect: this.scoreResult.isPerfect,
        date: new Date().toISOString()
      };

      // 保存到速判专用记录
      const records = Storage.get('speed_judge_records', []);
      records.unshift(record);

      // 只保留最近50条记录
      if (records.length > 50) {
        records.splice(50);
      }

      Storage.set('speed_judge_records', records);
    },

    // 格式化时间
    formatTime(seconds) {
      return CommonUtils.formatTime(seconds);
    },

    // 再次练习
    tryAgain() {
      uni.navigateTo({
        url: `/pages/speed-judge/practice?count=${this.questionData.fractions.length}`
      });
    },

    // 返回首页
    backToHome() {
      uni.switchTab({
        url: '/pages/index/index'
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 120rpx;
}

.result-header {
  padding: 60rpx 40rpx 40rpx;
  text-align: center;
  color: white;
  position: relative;

  &.result-perfect {
    background: linear-gradient(135deg, #f093fb, #f5576c);
  }

  &.result-good {
    background: linear-gradient(135deg, #a0f0ed, #67e8f9);
  }

  &.result-normal {
    background: linear-gradient(135deg, #43e97b, #38f9d7);
  }

  &.result-poor {
    background: linear-gradient(135deg, #fa709a, #fee140);
  }

  .result-icon {
    margin-bottom: 20rpx;
  }

  .result-title {
    font-size: 36rpx;
    font-weight: bold;
    margin-bottom: 15rpx;
  }

  .result-score {
    font-size: 48rpx;
    font-weight: bold;
  }
}

.score-details {
  background: white;
  margin: 30rpx 40rpx;
  border-radius: 15rpx;
  padding: 30rpx;
  box-shadow: 0 5rpx 15rpx rgba(0, 0, 0, 0.05);

  .detail-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx 0;
    border-bottom: 1rpx solid #f0f0f0;

    &:last-child {
      border-bottom: none;
    }

    .detail-label {
      font-size: 28rpx;
      color: #666;
    }

    .detail-value {
      font-size: 28rpx;
      font-weight: bold;
      color: #333;
    }
  }
}

.answer-review {
  margin: 0 40rpx 30rpx;

  .review-title {
    font-size: 30rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
  }

  .answer-list {
    background: white;
    border-radius: 15rpx;
    overflow: hidden;
    box-shadow: 0 5rpx 15rpx rgba(0, 0, 0, 0.05);
  }

  .answer-item {
    padding: 25rpx 30rpx;
    border-bottom: 1rpx solid #f0f0f0;

    &:last-child {
      border-bottom: none;
    }

    &.correct {
      background-color: #f8fff9;
      border-left: 6rpx solid #28a745;
    }

    &.wrong {
      background-color: #fff8f8;
      border-left: 6rpx solid #dc3545;
    }

    .answer-content {
      display: flex;
      align-items: center;
      justify-content: space-between;

      .fraction,
      .decimal {
        font-size: 28rpx;
        font-weight: bold;
        color: #333;
      }

      .connection-line {
        flex: 1;
        display: flex;
        justify-content: center;
        align-items: center;
        position: relative;

        &::before {
          content: '';
          position: absolute;
          left: 20%;
          right: 20%;
          height: 2rpx;
          background-color: currentColor;
          opacity: 0.3;
        }
      }
    }

    .correct-answer {
      margin-top: 15rpx;
      padding-top: 15rpx;
      border-top: 1rpx solid #f0f0f0;

      text {
        font-size: 24rpx;
        color: #dc3545;
      }
    }
  }
}

.actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  gap: 20rpx;
  padding: 30rpx 40rpx;
  background: white;
  box-shadow: 0 -5rpx 15rpx rgba(0, 0, 0, 0.1);
}

.action-btn {
  flex: 1;
  height: 80rpx;
  border: none;
  border-radius: 10rpx;
  font-size: 28rpx;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10rpx;

  &.secondary-btn {
    background-color: #f8f9fa;
    color: #007AFF;
    border: 2rpx solid #007AFF;
  }

  &.primary-btn {
    background: linear-gradient(135deg, #67e8f9, #38bdf8);
    color: white;
  }

  &:active {
    transform: scale(0.98);
  }
}
</style>